package cn.stu.common.utils;

import cn.hutool.core.text.CharSequenceUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

import static cn.stu.common.utils.SystemConstants.CACHE_MD5;
import static cn.stu.common.utils.SystemConstants.CACHE_MD5_TTL;

/**
 * PWD实用程序
 *
 * @author 郑志豪
 * @date 2023/09/27
 */
@Component
public class PwdUtils {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 按字符串获取MD5
     *
     * @param password 密码
     * @return {@link String}
     */
    public String getMd5ByString(String password) {
        String passwordMd5 = stringRedisTemplate.opsForValue().get(CACHE_MD5 + password);
        if (CharSequenceUtil.isNotBlank(passwordMd5)) {
            return passwordMd5;
        }
        passwordMd5 = DigestUtils.md5DigestAsHex(password.getBytes());
        stringRedisTemplate.opsForValue().set(CACHE_MD5 + password, passwordMd5);
        stringRedisTemplate.expire(CACHE_MD5 + password, CACHE_MD5_TTL, TimeUnit.SECONDS);
        return passwordMd5;
    }
}
